package com.hnichr.ump.business.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hnichr.ump.business.Constant;
import com.hnichr.ump.common.vo.wechat.PhoneInfoRespVo;
import org.springframework.stereotype.Service;

import com.hnichr.ump.common.doc.service.WeChatService;

import lombok.extern.slf4j.Slf4j;

import java.util.*;

/**
 * 微信相关接口的实现类
 */
@Service
@Slf4j
public class WeChatServiceImpl implements WeChatService {

	/**
	 * 小程序appId
	 */
	private static final String appId = "wx7086e514c6e7b7b8";

	/**
	 * 小程序appSecret
	 */
	private static final String appSecret = "3eb0fbc9b6a0792e3d87dfed920de016";

	/**
	 * 跳转小程序类型：developer为开发版；trial为体验版；formal为正式版；默认为正式版
	 */
	private static final String miniProgramState = "trial";

	@Override
	public void push(String content, String receiver) {
		log.info("开始推送微信消息：" + content);
		//todo 需要调用方传openId, orderId, orderNo, bizType
//		sendMessage(receiver, "fe3141c8-8e98-4602-830e-176fdd91191c", "D221216175106NXY190QX", "10");
	}

	/**
	 * 获取accessToken
	 * @return token
	 */
	@Override
	public String getAccessToken() {
		String tokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
		tokenUrl = tokenUrl.replace("APPID", appId);
		tokenUrl = tokenUrl.replace("APPSECRET", appSecret);
		String result = HttpUtil.createGet(tokenUrl).execute().body();
		log.info("获取accessToken result:{}", result);
		JSONObject jsonObject = JSONUtil.parseObj(result);
		Object accessToken = jsonObject.get("access_token");
		return (String) accessToken;
	}

	/**
	 * 小程序登录，获取openId
	 * @param code 登录授权码
	 * @return 用户信息
	 */
	@Override
	public String getOpenId(String code) {
		String loginUrl = "https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code";
		loginUrl = loginUrl.replace("APPID", appId);
		loginUrl = loginUrl.replace("SECRET", appSecret);
		loginUrl = loginUrl.replace("JSCODE", code);
		String result = HttpUtil.createGet(loginUrl).execute().body();
		log.info("获取login result:{}", result);
		JSONObject jsonObject = JSONUtil.parseObj(result);
		return jsonObject.getStr("openid");
	}

	/**
	 * 获取类目
	 * @return 类目列表
	 */
	public JSONArray getCategory() {
		String accessToken = getAccessToken();
		String getCategoryUrl = "https://api.weixin.qq.com/wxaapi/newtmpl/getcategory?access_token=ACCESS_TOKEN";
		getCategoryUrl = getCategoryUrl.replace("ACCESS_TOKEN", accessToken);
		String result = HttpUtil.createGet(getCategoryUrl).execute().body();
		log.info("获取getCategory result:{}", result);
		JSONObject jsonObject = JSONUtil.parseObj(result);
		return jsonObject.getJSONArray("data");
	}

	/**
	 * 获取模板
	 * @return 模板列表
	 */
	public JSONArray getPubTemplateTitleList() {
		String accessToken = getAccessToken();
		String getPubTempListUrl = "https://api.weixin.qq.com/wxaapi/newtmpl/getpubtemplatetitles?access_token=ACCESS_TOKEN&ids=IDS&start=0&limit=10";
		getPubTempListUrl = getPubTempListUrl.replace("ACCESS_TOKEN", accessToken);
		getPubTempListUrl = getPubTempListUrl.replace("IDS", "1279,774");
		String result = HttpUtil.createGet(getPubTempListUrl).execute().body();
		log.info("获取getPubTemplateTitleList result:{}", result);
		JSONObject jsonObject = JSONUtil.parseObj(result);
		return jsonObject.getJSONArray("data");
	}

	/**
	 * 获取模板下的关键词列表
	 * @return 关键词列表
	 */
	public JSONArray getKeywordList() {
		String accessToken = getAccessToken();
		String getKeywordListUrl = "https://api.weixin.qq.com/wxaapi/newtmpl/getpubtemplatekeywords?access_token=ACCESS_TOKEN&tid=TID";
		getKeywordListUrl = getKeywordListUrl.replace("ACCESS_TOKEN", accessToken);
		getKeywordListUrl = getKeywordListUrl.replace("TID", "1330");
		String result = HttpUtil.createGet(getKeywordListUrl).execute().body();
		log.info("获取getKeywordList result:{}", result);
		JSONObject jsonObject = JSONUtil.parseObj(result);
		return jsonObject.getJSONArray("data");
	}

	/**
	 * 添加模板
	 * @return 模板id
	 */
	public String addMessageTemplate() {
		String accessToken = getAccessToken();
		String sendMessageUrl = "https://api.weixin.qq.com/wxaapi/newtmpl/addtemplate?access_token=ACCESS_TOKEN";
		sendMessageUrl = sendMessageUrl.replace("ACCESS_TOKEN", accessToken);
		Map<String, Object> map = new HashMap<>();
		map.put("tid", "1305");
		List<Integer> kidList = new ArrayList<>();
		kidList.add(1);
		kidList.add(4);
		kidList.add(12);
		map.put("kidList", kidList.toArray());
		map.put("miniprogram_state", "developer");
		map.put("sceneDesc", "添加模板描述");
		String result = HttpUtil.createPost(sendMessageUrl).body(JSONUtil.toJsonStr(map)).execute().body();
		log.info("获取addMessageTemplate result:{}", result);
		JSONObject jsonObject = JSONUtil.parseObj(result);
		return jsonObject.getStr("priTmplId");
	}

	/**
	 * 获取个人模板列表
	 * @return 模板列表
	 */
	public JSONArray getMessageTemplateList() {
		String accessToken = getAccessToken();
		String getPubTempListUrl = "https://api.weixin.qq.com/wxaapi/newtmpl/gettemplate?access_token=ACCESS_TOKEN";
		getPubTempListUrl = getPubTempListUrl.replace("ACCESS_TOKEN", accessToken);
		String result = HttpUtil.createGet(getPubTempListUrl).execute().body();
		log.info("获取getMessageTemplateList result:{}", result);
		JSONObject jsonObject = JSONUtil.parseObj(result);
		return jsonObject.getJSONArray("data");
	}

	/**
	 * 发送订阅消息
	 * @param openId
	 * @param orderId
	 * @param orderNo
	 * @param bizType
	 * @return
	 */
	@Override
	public JSONObject sendMessage(String openId, String orderId, String orderNo, String bizType) {
		String accessToken = getAccessToken();
		String sendMessageUrl = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=ACCESS_TOKEN";
		sendMessageUrl = sendMessageUrl.replace("ACCESS_TOKEN", accessToken);
		Map<String, Object> map = new HashMap<>();
		map.put("touser", openId);
		map.put("template_id", "f02pSF6NO9kFheeHdpLyb2Lj9G7VD4KCFyQiWn8Tuyc");
		map.put("page", "/pages/orderDetails/orderDetails?rid=" + orderId + "&orderNo=" + orderNo);
		map.put("miniprogram_state", miniProgramState);
		map.put("lang", "zh_CN");
		Map<String, Object> data = new HashMap<>();
		Map<String, String> valueMap1 = new HashMap<>();
		valueMap1.put("value", orderNo);
		data.put("character_string1", valueMap1);
		Map<String, String> valueMap3 = new HashMap<>();
		valueMap3.put("value", DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
		data.put("date4", valueMap3);
		Map<String, String> valueMap2 = new HashMap<>();
		valueMap2.put("value", getBizTypeStr(bizType));
		data.put("thing12", valueMap2);
		map.put("data", data);
		String result = HttpUtil.createPost(sendMessageUrl).body(JSONUtil.toJsonStr(map)).execute().body();
		log.info("获取sendMessage result:{}", result);
		return JSONUtil.parseObj(result);
	}

	/**
	 * 获取业务类型
	 * @param bizType
	 * @return
	 */
	private String getBizTypeStr(String bizType) {
		if (Constant.DOC_BIZ_TYPE_10.equals(bizType)) {
			return "打印";
		} else if (Constant.DOC_BIZ_TYPE_20.equals(bizType)) {
			return "名片制作";
		} else if (Constant.DOC_BIZ_TYPE_30.equals(bizType)) {
			return "条幅制作";
		} else if (Constant.DOC_BIZ_TYPE_40.equals(bizType)) {
			return "排版";
		} else if (Constant.DOC_BIZ_TYPE_50.equals(bizType)) {
			return "线上设计";
		}
		return "未知";
	}

//	public static void main(String[] args) {
//		JSONArray dataList = new WeChatServiceImpl().getMessageTemplateList();
//		if (CollectionUtils.isNotEmpty(dataList)) {
//			for (int i = 0;i<dataList.size();i++) {
//				JSONObject object = dataList.getJSONObject(i);
//				System.err.println(object.toString());
//			}
//		}
//		JSONObject jsonObject = new WeChatServiceImpl().sendMessage("otLKr4uLs9geUjleoS_7q5q2eI0E", "fe3141c8-8e98-4602-830e-176fdd91191c","D221216175106NXY190QX1", "20");
//		System.err.println(jsonObject.toString());
//	}

	/**
	 * 获取手机号信息
	 * @param accessToken token
	 * @param code 手机号凭证
	 * @return 手机号信息
	 */
	@Override
	public PhoneInfoRespVo getPhoneInfo(String accessToken, String code) {
		String url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=ACCESS_TOKEN";
		url = url.replace("ACCESS_TOKEN", accessToken);
		Map<String, String> map = new HashMap<>();
		map.put("code", code);
		String result = HttpUtil.createPost(url).body(JSONUtil.toJsonStr(map)).execute().body();
		log.info("获取手机号信息 result:{}", result);
		PhoneInfoRespVo phoneInfoRespVo = JSONUtil.toBean(result, PhoneInfoRespVo.class);
		if (0 != phoneInfoRespVo.getErrcode()) {
			return null;
		}
		return phoneInfoRespVo;
	}

}
